package com.ruoyi.system.bargain.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.operation.service.IOperationHistoryService;
import com.ruoyi.system.bargain.domain.PangXieBargainReq;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.model.domain.OperationHistory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @other pzz
 * @data 2024/8/31
 * @apiNote
 */
@Slf4j
@RestController
@RequestMapping("/business/pangxie/bargain")
public class PXBargainSaleController extends BaseController {
    @Resource
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private IOperationHistoryService operationHistoryService;
    @Autowired
    private RedisCache redisCache;
    static String TOKEN_authorization = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJQWEI3LUJVU0lORVNTLkFQSSIsImV4cCI6MTcyNTI4NTI3MywiYXVkIjoiYWRtaW4iLCJuYmYiOjE3MjUyNDIwNzMsImlhdCI6MTcyNTI0MjA3MywidXNlciI6eyJ1c2VyX2lkIjoxMDAsInVzZXJfbmFtZSI6Ilx1NzlkZlx1NmUzOFx1NGU1MCIsIm51bWJlciI6Inp5bCIsImNvbnRhY3QiOiJcdTlhNmNcdTVmNjZcdThmODkiLCJxcSI6IjE4MzkzOTQ5Mzc2IiwidGVsZXBob25lIjoiMTgzOTM5NDkzNzYiLCJ3eCI6IjE4MzkzOTQ5Mzc2IiwiZ2FtZUlkcyI6WyIxMyIsIjI2IiwiMjMiLCIxMSIsIjQwIiwiMzIiLCIzMyIsIjEyIiwiMzYiLCIxNDgiLCI0MDkiXX19.qtPN8rJEYHHbK_5pLqOvC6Qlp6CdgBgqOWlaVeJIrqI";
    @PostMapping("/list")
    public AjaxResult list(@RequestBody PangXieBargainReq req) {
        getPXToken();
        System.out.println("请求参数 :" + JSONObject.toJSONString(req));
        String url = "http://api-merchant.pxb7.com/business/bargain/list";
        Map<String, String> header = new HashMap<>();
        header.put("authorization" , TOKEN_authorization);
        header.put("content-type" , "application/json;charset=UTF-8");

        Map<String, String> params = new HashMap<>();
        params.put("game_account" , req.getGameAccount());
        params.put("keyword" , req.getKeyword());
        params.put("page" , req.getPage()+"");
        params.put("pageSize" , req.getPageSize()+"");
        params.put("status" , req.getStatus());
        try {
            String sendPost = HttpUtils.sendPost(url, JSONObject.toJSONString(params), header);
            log.info(sendPost);
            return AjaxResult.success(JSONObject.parseObject(sendPost).getJSONObject("data"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success();
    }

    @PostMapping("/bargainBack")
    public AjaxResult bargainBack(@RequestBody PangXieBargainReq req) {
        getPXToken();
        String url = "http://api-merchant.pxb7.com/business/bargain/bargainBack";
        Map<String, String> header = new HashMap<>();
        header.put("authorization" , TOKEN_authorization);
        header.put("content-type" , "application/json;charset=UTF-8");

        Map<String, String> params = new HashMap<>();
        params.put("id" , req.getId());
        params.put("sell_price" , req.getSellPrice());

        try {
            String sendPost = HttpUtils.sendPost(url, JSONObject.toJSONString(params), header);
            log.info(sendPost);
            setOper("螃蟹砍价","商品id:"+req.getId() +"  还价"+req.getSellPrice() );

            return AjaxResult.success(JSONObject.parseObject(sendPost).getJSONObject("data"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success();
    }

    @PostMapping("/deal")
    public AjaxResult deal(@RequestBody PangXieBargainReq req) {
        getPXToken();
        String url = "http://api-merchant.pxb7.com/business/bargain/deal";
        Map<String, String> header = new HashMap<>();
        header.put("authorization" , TOKEN_authorization);
        header.put("content-type" , "application/json;charset=UTF-8");

        Map<String, String> params = new HashMap<>();
        params.put("id" , req.getId());
        params.put("status" , req.getStatus());

        if (StringUtils.equals(req.getStatus(), "2")) {
            setOper("螃蟹砍价接受", "商品id:" + req.getId());
        } else if (StringUtils.equals(req.getStatus(), "3")) {
            setOper("螃蟹砍价拒绝", "商品id:" + req.getId());
        }
        try {
            String sendPost = HttpUtils.sendPost(url, JSONObject.toJSONString(params), header);
            log.info(sendPost);
            return AjaxResult.success(JSONObject.parseObject(sendPost).getJSONObject("data"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success();
    }

    public void getPXToken() {
        String token = (String) redisCache.getCacheObject("PX_BARGAIN_TOKEN");
        if (StringUtils.isNotEmpty(token)) {
            TOKEN_authorization = token;
        }
        String url1 = "http://api-merchant.pxb7.com/business/login";
        Map<String, String> params1 = new HashMap<>();

        List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataByType("pangxie_bargainBack");
        for (SysDictData dictData : sysDictDataList) {
            if ("username".equals(dictData.getDictLabel())) {
                params1.put("user_name", dictData.getDictValue());
            }
            if ("password".equals(dictData.getDictLabel())) {
                params1.put("password", dictData.getDictValue());
            }
        }

        String response = com.ruoyi.system.outto.dto.yx7881.utils.HttpUtil.doPost(url1, params1);
        JSONObject jsonObject = JSONObject.parseObject(response);

        if ("200".equals(jsonObject.getString("code"))) {
            String data = jsonObject.getString("data");
            JSONObject jsonObject1 = jsonObject.parseObject(data);
            log.info("token={}" , jsonObject1.getString("token"));
            TOKEN_authorization = jsonObject1.getString("token");
            redisCache.setCacheObject("PX_BARGAIN_TOKEN" , token, 3, TimeUnit.MINUTES);
        }
    }

    //操作记录
    private void setOper(String operation,String reason) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        OperationHistory operationHistory = new OperationHistory();
        operationHistory.setOperator(loginUser.getUsername());
        operationHistory.setOperatTime(new Date());
        operationHistory.setStatus(operation);
        operationHistory.setReason(reason);
        operationHistoryService.insertOperationHistory(operationHistory);
    }
}
